﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Domain.QualityInspection_Modelling;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using MES.Server.API.Dto.QualityInspection_DTO;
using Microsoft.EntityFrameworkCore;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler.NewQualityInspectionCommandHandler
{
    /// <summary>
    /// 质检记录查询命令处理器（三表联查实现）
    /// </summary>
    public class QualityInspectionQueryCommandHandler : IRequestHandler<QualityInspectionQueryCommand, ApiResult<ApiPaging<QualityInspectionDTO>>>
    {
        // 注入三个实体的仓储
        private readonly IRepository<QualityInspection> _qualityRepo;
        private readonly IRepository<ProduceModel> _produceRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;

        public QualityInspectionQueryCommandHandler(
            IRepository<QualityInspection> qualityRepo,
            IRepository<ProduceModel> produceRepo,
            IRepository<MaterialGroupModel> materialGroupRepo)
        {
            _qualityRepo = qualityRepo;
            _produceRepo = produceRepo;
            _materialGroupRepo = materialGroupRepo;
        }

        public async Task<ApiResult<ApiPaging<QualityInspectionDTO>>> Handle(QualityInspectionQueryCommand request, CancellationToken cancellationToken)
        {
            // 初始化返回结果
            var result = new ApiResult<ApiPaging<QualityInspectionDTO>>
            {
                Code = StatusCode.Success,
                Message = "查询成功"
            };

            // 1. 三表联查（质检记录 -> 生产工单 -> 物料群组）
            var query = from quality in _qualityRepo.GetAll()
                            // 关联生产工单（质检.ProductionOrderId = 生产工单.Id）
                        join produce in _produceRepo.GetAll()
                            on quality.ProductionOrderId equals produce.Id
                        // 关联物料群组（生产工单.MaterialGroupId = 物料群组.Id）
                        join materialGroup in _materialGroupRepo.GetAll()
                            on produce.MaterialGroupId equals materialGroup.Id
                        // 排除逻辑删除的记录（基于AuditEntity的IsDel字段）
                        where !quality.IsDel && !produce.IsDel && !materialGroup.IsDel
                        select new QualityInspectionDTO
                        {
                            // 质检记录字段
                            Id = quality.Id,
                            InspectionNumber = quality.InspectionNumber,
                            InspectedQuantity = quality.InspectedQuantity,
                            QualifiedQuantity = quality.QualifiedQuantity,
                            UnqualifiedQuantity = quality.UnqualifiedQuantity,
                            Inspector = quality.Inspector,
                            InspectionTime = quality.InspectionTime,

                            // 生产工单字段
                            ProductionOrderId = produce.Id,
                            ProduceCode = produce.ProduceCode,
                            ProduceName = produce.ProduceName,
                            ProduceType = produce.ProduceType,
                            StartDate = produce.StartDate,
                            EntDate = produce.EntDate,
                            ProduceNum = produce.ProduceNum,

                            // 物料群组字段
                            MaterialGroupId = materialGroup.Id,
                            MaterialGroupCode = materialGroup.MaterialGroupCode,
                            MaterialGroupName = materialGroup.MaterialGroupName,
                            MaterialGroupType = materialGroup.MaterialGroupType,
                            MaterialGroupDesc = materialGroup.MaterialGroupDesc
                        };

            // 2. 条件筛选（支持可空参数，仅当有值时应用筛选）
            if (!string.IsNullOrWhiteSpace(request.MaterialGroupCode))
            {
                // 物料群组编号精确匹配（下拉框筛选）
                query = query.Where(dto => dto.MaterialGroupCode == request.MaterialGroupCode);
            }
            if (!string.IsNullOrWhiteSpace(request.ProduceCode))
            {
                // 生产编号精确匹配（下拉框筛选）
                query = query.Where(dto => dto.ProduceCode == request.ProduceCode);
            }
            if (!string.IsNullOrWhiteSpace(request.InspectionNumber))
            {
                // 质检单号模糊查询（文本框筛选）
                query = query.Where(dto => dto.InspectionNumber.Contains(request.InspectionNumber));
            }

            // 3. 分页处理
            int totalCount = query.Count(); // 总条数
            var pagedData = query
                .OrderByDescending(dto => dto.InspectionTime) // 按质检时间倒序
                .Skip((request.Index - 1) * request.Size) // 跳过前N条
                .Take(request.Size) // 获取当前页数据
                .ToList();

            // 4. 构造分页结果
            var pagingResult = new ApiPaging<QualityInspectionDTO>
            {
                Totalcount = totalCount,
                TotalPage = pagedData
            };

            result.Data = pagingResult;
            return await Task.FromResult(result);
        }
    }
}
